<template>
  <yc-container spacious>
    <yc-search-panel slot="header" v-model="active">
      <yc-bar slot="title">
        <yc-bar-space />
        <yc-bar-cell>
          <yc-pagination :full="false" @change="handlePageChange" :pagination="pagination" />
        </yc-bar-cell>
        <yc-bar-space />
        <yc-bar-cell>
          <el-button-group>
            <yc-button size="mini" icon="el-icon-refresh" label="刷新" @click="handleFetchTableData" />
            <yc-button size="mini" icon="el-icon-set-up" label="搜索设置" @click="handleSearchSetting" />
            <yc-button size="mini" icon="el-icon-set-up" label="表头设置" @click="handleSettingTable" />
          </el-button-group>
        </yc-bar-cell>
        <yc-bar-cell>
          <yc-button type="primary" size="mini" icon="el-icon-plus" label="新增" v-permission="['management:user:add']"
            @click="handleCreate" />
        </yc-bar-cell>
      </yc-bar>
      <yc-form ref='form' v-model="searchCopy" :setting="formSetting" :itemSetting="searchFormItems" />
    </yc-search-panel>
    <yc-table height="100%" ref="table" :api="api" :columns="columns" :pagination="pagination"
      :checkbox-config="{checkMethod}" highlight-current-row>
      <template v-slot:multiple="{ row , column }">
        <template v-if="row[column.property] && row[column.property].length">
          <el-tag size="mini" v-for="(item,index) in row[column.property]" :key="index" style="margin-right: 5px;">
            {{item.name}}</el-tag>
        </template>
        <template v-else>
          /
        </template>
      </template>
      <template v-slot:moreOperation="{ row }">
        <yc-button type="text" size="mini" label="编辑" v-permission="['management:user:update']"
          @click="handleUpdate(row)" />
        <yc-button :disabled="isAdministrator(row)" size="mini" type="text" label="删除"
          v-permission="['management:user:delete']" @click="$refs.table.handleDeleteRow(row)" />
      </template>
      <template v-slot:switchOperation="{row}">
        <el-switch v-model="row.status" activeColor='#13ce66' inactiveColor='#ff4949' :activeValue='activeValue'
          :inactiveValue='inactiveValue' :disabled="isAdministrator(row)" @change="handleChangeStatus({row})">
        </el-switch>
      </template>
      <template v-slot:showName="{row,column}">
        {{row[column.field] ? row[column.field].name : '/'}}
      </template>
    </yc-table>
    <yc-bar slot=" footer">
      <!-- <yc-bar-cell>
        <yc-button type="primary" size="mini" icon="el-icon-tickets" label="全选" @click="handleAllSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document-copy" label="反选" @click="handleInvertSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document" label="全不选" @click="handleAllNoneSelection" />
        <yc-button type="danger" size="mini" icon="el-icon-delete" label="删除" v-permission="['management:user:delete']"
          @click="handleDeleteTable" />
      </yc-bar-cell> -->
      <yc-bar-space />
      <yc-bar-cell>
        <vxe-pager size="mini" @page-change="handlePageChange" :page-sizes="[25, 50, 100, 150]"
          :current-page="pagination.current" :page-size="pagination.size" :total="pagination.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']">
        </vxe-pager>
      </yc-bar-cell>
    </yc-bar>
    <yc-dialog width="600px" :mode="mode" :conf="dialogConf" @on-submit="handleSubmit">
      <yc-form ref="userForm" v-model="formData" :setting="userFormSetting" :itemSetting="userFormItemSetting" />
    </yc-dialog>
    <yc-search-setting-panel :defaultValue="searchFields" @change="searchSettingChange" :conf="searchDialogConf" />
  </yc-container>
</template>

<script>

import { queryUsers, addUser, updateUser, removeUser } from '@api/management/user'
import { queryPosts } from '@api/management/post'
import { queryDepts } from '@/api/management/dept'
import { queryRoles } from '@/api/management/role'
import util from '@/libs/util'
import crud from '@/mixins/crud'
export default {
  name: 'user',
  mixins: [crud],
  data () {
    return {
      api: {
        index: queryUsers,
        modify: updateUser,
        del: removeUser
      },
      mode: 'create',
      columns: [
        { key: 'checkbox', type: 'checkbox', width: '50', fixed: 'left' },
        { key: 'seq', type: 'seq', width: '50', fixed: 'left' },
        { key: 'avatar', field: 'avatar', title: '头像', width: '100', cellRender: { name: 'pictrue', domain: process.env.VUE_APP_SERVER }, fixed: 'left' },
        { key: 'username', field: 'username', width: '120', title: '用户名', formatter: 'formatEmpty', fixed: 'left' },
        { key: 'nickname', field: 'nickname', width: '120', title: '昵称', formatter: 'formatEmpty', fixed: 'left' },
        { key: 'email', field: 'email', title: '邮箱', formatter: 'formatEmpty', width: '150' },
        { key: 'age', field: 'age', title: '年龄', formatter: 'formatEmpty', width: '100' },
        { key: 'sexText', field: 'sexText', title: '性别', width: '100', formatter: 'formatEmpty' },
        { key: 'phone', field: 'phone', title: '电话', formatter: 'formatEmpty', width: '150' },
        { key: 'roleList', field: 'roleList', title: '角色', width: '200', slots: { default: 'multiple' } },
        { key: 'post', field: 'post', title: '岗位', width: '200', slots: { default: 'showName' } },
        { key: 'dept', field: 'dept', title: '部门', slots: { default: 'showName' }, width: '150' },
        { key: 'lastLoginTime', field: 'lastLoginTime', title: '最后登录时间', width: '150' },
        { key: 'remark', field: 'remark', title: '备注', formatter: 'formatEmpty', width: '150' },
        { key: 'createTime', field: 'createTime', title: '创建日期', width: '150' },
        { key: 'status', field: 'status', width: '120', title: '状态', fixed: 'right', slots: { default: 'switchOperation' } },
        { key: 'operation', title: '操作', width: '120', slots: { default: 'moreOperation' }, fixed: 'right' }
      ],
      formSetting: {
        useLayout: false,
        inline: true,
        size: 'mini',
        labelPosition: 'top'
      },
      dialogConf: {
        dialogVisible: false
      },
      formData: {},
      selectRow: null,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeLoading: true,
      searchCopy: {},
      selectRoles: [],
      selectPosts: [],
      selectDepts: [],
      activeValue: 1,
      inactiveValue: 0
    }
  },
  computed: {
    formItemSetting () {
      return [
        {
          prop: 'username',
          default: '',
          title: '用户名',
          col: { span: 4 },
          name: 'input',
          clearable: true,
          visible: true,
          placeholder: '请输入用户名',
          general: true
        },
        {
          prop: 'roleIds',
          default: [],
          title: '角色',
          col: { span: 4 },
          name: 'select-multiple',
          clearable: true,
          multiple: true,
          visible: true,
          placeholder: '请选择角色',
          options: this.selectRoles
        },
        {
          prop: 'postIds',
          default: [],
          title: '岗位',
          col: { span: 4 },
          name: 'select-multiple',
          clearable: true,
          multiple: true,
          visible: true,
          placeholder: '请选择岗位',
          options: this.selectPosts
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 4 },
          name: 'dict-select',
          dictName: 'normal_status',
          visible: true
        }
      ]
    },
    userFormSetting () {
      return {
        useLayout: true,
        inline: false,
        size: 'mini',
        labelPosition: 'right',
        labelWidth: '80px'
      }
    },
    userFormItemSetting () {
      return [
        {
          prop: 'username',
          default: '',
          title: '用户名',
          col: { span: 12 },
          name: 'input',
          clearable: true,
          rule: { required: true, message: '请输入用户名', trigger: 'blur' },
          disabled: this.isAdministrator(this.formData),
          visible: true,
          placeholder: '请输入用户名'
        },
        {
          prop: 'phone',
          default: '',
          title: '电话',
          col: { span: 12 },
          name: 'input',
          clearable: true,
          rule: { required: true, message: '请输入电话', trigger: 'blur' },
          visible: true,
          placeholder: '请输入电话'
        },
        {
          prop: 'nickname',
          default: '',
          title: '昵称',
          col: { span: 12 },
          name: 'input',
          clearable: true,
          rule: { required: true, message: '请输入昵称', trigger: 'change' },
          visible: true,
          placeholder: '请输入昵称'
        },
        {
          prop: 'email',
          default: '',
          title: '邮箱',
          col: { span: 12 },
          name: 'input',
          clearable: true,
          rule: { required: true, message: '请输入邮箱', trigger: 'blur' },
          visible: true,
          placeholder: '请输入邮箱'
        },
        {
          prop: 'deptId',
          default: null,
          title: '部门',
          col: { span: 12 },
          name: 'treeselect',
          visible: true,
          clearable: true,
          placeholder: '请选择部门',
          normalizer: (node) => {
            return {
              id: node.id,
              label: node.name,
              children: node.children
            }
          },
          options: this.selectDepts
        },
        {
          prop: 'postId',
          default: [],
          title: '岗位',
          col: { span: 12 },
          name: 'select',
          clearable: true,
          visible: true,
          placeholder: '请选择岗位',
          options: this.selectPosts
        },
        {
          prop: 'remark',
          default: '',
          title: '备注',
          col: { span: 12 },
          name: 'input',
          clearable: true,
          visible: true,
          placeholder: '请输入备注'
        },
        {
          prop: 'sex',
          default: -1,
          title: '性别',
          clearable: true,
          col: { span: 12 },
          name: 'dict-select',
          dictName: 'sex_type',
          all: false,
          visible: true
        },
        {
          prop: 'roleIds',
          default: [],
          title: '角色',
          col: { span: 24 },
          name: 'select-multiple',
          clearable: true,
          multiple: true,
          visible: true,
          disabled: this.isAdministrator(this.formData),
          placeholder: '请选择角色',
          all: false,
          options: this.selectRoles
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 12 },
          name: 'dict-radio',
          dictName: 'normal_status',
          disabled: this.isAdministrator(this.formData),
          visible: true
        }
      ]
    }
  },
  created () {
    this.fetchDeptData()
    this.fetchRoleData()
    this.fetchPostData()
  },
  mounted () {
  },
  methods: {
    fetchDeptData () {
      this.treeLoading = true
      queryDepts().then(res => {
        var { data } = res
        if (data && data.length) {
          this.treeData = util.treeData(data)
          this.selectDepts = util.treeData(data)
        }
        this.treeLoading = false
      })
    },
    fetchRoleData () {
      queryRoles().then(res => {
        var { data } = res
        if (data && data.length) {
          this.selectRoles = data.map(e => {
            return {
              label: e.name,
              value: e.id
            }
          })
        }
      })
    },
    fetchPostData () {
      queryPosts().then(res => {
        var { data } = res
        if (data && data.length) {
          this.selectPosts = data.map(e => {
            return {
              label: e.name,
              value: e.id
            }
          })
        }
      })
    },
    handleCreate () {
      this.mode = 'create'
      this.formData = {}
      this.dialogConf.dialogVisible = true
    },
    handleUpdate (row) {
      this.mode = 'update'
      this.selectRow = row
      this.formData = this.$_.cloneDeep(row)
      if (row.postList && row.postList.length) {
        this.formData.postIds = row.postList.map(e => { return e.id })
      }
      if (row.roleList && row.roleList.length) {
        this.formData.roleIds = row.roleList.map(e => { return e.id })
      }
      this.dialogConf.dialogVisible = true
    },
    handleSubmit (callBack) {
      var record = this.formData
      if (this.mode === 'create') {
        addUser(record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('添加成功')
            this.$refs.table.insertRow(data, null, null)
          } else {
            this.$message.error('添加失败')
          }
          callBack(code === 200)
        })
      } else {
        updateUser(record.id, record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.$refs.table.updateRow(this.selectRow, data)
            this.selectRow = null
          } else {
            this.$message.error('修改失败')
          }
          callBack(code === 200)
        })
      }
    },
    handleNodeClick (data) {
      this.search.deptId = data.id
      this.handleFetchTableData()
    },
    isAdministrator (row) {
      return row.username === 'administrator'
    },
    checkMethod ({ row }) {
      return !this.isAdministrator(row)
    },
    customFetchTableData () {
      this.search = this.$_.cloneDeep(this.searchCopy)
      if (this.searchCopy.roleIds && this.searchCopy.roleIds.length) {
        this.search.roleIds = this.searchCopy.roleIds.join(',')
      }
      if (this.searchCopy.postIds && this.searchCopy.postIds.length) {
        this.search.postIds = this.searchCopy.postIds.join(',')
      }
      this.handleFetchTableData()
    },
    customResetTableData () {
      this.searchCopy = {}
      this.handleRestTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-container {
  width: 100%;
  height: 100%;
}
.el-aside {
  width: 15% !important;
  border: 1px solid #e8eaec;
  margin-right: 20px;
  padding: 0px 0px 0px 10px;
  height: 100%;
}
.el-main {
  padding: 0px !important;
}
.el-scrollbar {
  height: 100%;
  ::v-deep.el-scrollbar__wrap {
    overflow-x: hidden;
    margin-bottom: 0px !important;
    ::v-deep.el-scrollbar__view {
      height: 100%;
    }
  }
}
</style>
